#include "input_color.h"
#include <QColorDialog>

InputColor::InputColor(QWidget *parent, const QString& name)
    : QLineEdit(parent), WidgetInput(name)
{
    this->setReadOnly(true);
}

void InputColor::setValue(const QString &value)
{
    QString val = value;
    while (val.startsWith('\'')) val.remove(0, 1);
    while (val.endsWith('\'')) val.remove(val.length() - 1, 1);
    this->setText(val);
    this->setStyleSheet("background-color:#" + val.mid(7) + val.mid(1, 6));
}

QString InputColor::getValue() const
{
    return "'" + this->text() + "'";
}

bool InputColor::isEmpty() const
{
    return this->text().isEmpty();
}

void InputColor::mousePressEvent(QMouseEvent*)
{
    QString value = this->text();
    QString argb = value.mid(7) + value.mid(1, 6);
    QColor color = QColorDialog::getColor(QColor::fromRgba(argb.toUInt(nullptr, 16)),
        this,
        "请选择颜色",
        QColorDialog::ShowAlphaChannel | QColorDialog::DontUseNativeDialog);
    if (color.isValid())
    {
        QString rgba = QString("#%1%2%3%4")
                           .arg(color.red(), 2, 16, QLatin1Char('0'))
                           .arg(color.green(), 2, 16, QLatin1Char('0'))
                           .arg(color.blue(), 2, 16, QLatin1Char('0'))
                           .arg(color.alpha(), 2, 16, QLatin1Char('0')).toUpper();
        this->setText(rgba);
        this->setStyleSheet("background-color:#" + rgba.mid(7) + rgba.mid(1, 6));
        emit editingFinished();
    }
}
